<template>
  <div class="work-order-app">
    <div class="app-header">
      <h1>材料送检工单管理</h1>
    </div>

    <div class="main-content">
      <!-- 数据录入区域 -->
      <div class="card input-card">
        <div class="card-header">
          <h2>新增送检记录</h2>
        </div>
        <div class="card-body">
          <div class="form-grid">
            <div class="form-group">
              <label for="furnaceNumber" class="form-label">炉号</label>
              <input
                v-model="furnaceNumber"
                @keyup.enter="handleEnter"
                placeholder="输入炉号后按回车确认"
                id="furnaceNumber"
                class="form-control"
                :disabled="isLoading"
              />
              <p class="form-hint">输入完成后按回车键快速添加（秒数自动获取当前时间）。</p>
              <p v-if="errorMsg" class="form-error">{{ errorMsg }}</p>
            </div>
            <div class="form-group">
              <label for="receiveTime" class="form-label">样品接收时间（24小时制）</label>
              <input
                type="datetime-local"
                v-model="receiveTime"
                id="receiveTime"
                class="form-control"
                :step="60"
                @change="formatTimeTo24h"
                :disabled="isLoading"
              />
              <p class="form-hint">格式：年-月-日 时:分（秒数自动填充当前时间）</p>
            </div>
          </div>
          <!-- 加载状态提示 -->
          <div v-if="isLoading" class="loading-overlay">
            <div class="loading-spinner"></div>
            <p class="loading-text">提交中...</p>
          </div>
        </div>
      </div>

      <!-- 工单列表区域 -->
      <div class="card table-card">
        <div class="card-header">
          <h2>送检工单列表</h2>
        </div>
        <div class="card-body">
          <div class="search-container">
            <input
              v-model="searchQuery"
              placeholder="搜索炉号..."
              class="form-control search-input"
            />
          </div>
          <div class="table-responsive">
            <table class="work-order-table">
              <thead>
                <tr>
                  <th>炉号</th>
                  <th>样品接收时间（24小时制）</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in filteredWorkOrders" :key="item.id" class="table-row">
                  <td>{{ item.furnaceNumber }}</td>
                  <td>{{ item.receiveTime }}</td>
                </tr>
                <tr v-if="filteredWorkOrders.length === 0 && !isTableLoading">
                  <td colspan="2" class="no-data">
                    <p>暂无数据</p>
                    <p class="no-data-hint">在上方输入炉号并按回车添加第一条记录。</p>
                  </td>
                </tr>
                <tr v-if="isTableLoading">
                  <td colspan="2" class="loading-data">
                    <div class="loading-spinner small"></div>
                    <p>加载数据中...</p>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- 成功提示弹窗 -->
    <div v-if="showSuccess" class="toast success-toast">
      <p><i class="icon-check"></i> 提交成功！</p>
    </div>

    <!-- 错误提示弹窗 -->
    <div v-if="showError" class="toast error-toast">
      <p><i class="icon-error"></i> {{ errorMsg }}</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'WorkOrderManagement',
  data() {
    return {
      furnaceNumber: '', // 炉号输入值
      receiveTime: '', // 时间控件值（YYYY-MM-DDTHH:mm）
      workOrders: [], // 工单列表数据
      searchQuery: '', // 搜索关键词
      isLoading: false, // 提交加载状态
      isTableLoading: false, // 表格加载状态
      errorMsg: '', // 错误信息
      showSuccess: false, // 成功提示弹窗
      showError: false, // 错误提示弹窗
      successTimer: null, // 成功提示定时器
      errorTimer: null // 错误提示定时器
    };
  },
  computed: {
    // 过滤后的工单列表
    filteredWorkOrders() {
      if (!this.searchQuery) {
        return this.workOrders;
      }
      const query = this.searchQuery.toLowerCase();
      return this.workOrders.filter(item =>
        item.furnaceNumber.toLowerCase().includes(query)
      );
    }
  },
  mounted() {
    // 初始化时间为当前北京时间（到分钟）
    this.setCurrentBeijingTimeToMinute();
    // 页面加载时获取已有工单列表
    this.fetchWorkOrders();
  },
  beforeUnmount() {
    // 清除定时器，避免内存泄漏
    clearTimeout(this.successTimer);
    clearTimeout(this.errorTimer);
  },
  methods: {
    /**
     * 初始化当前北京时间（到分钟，适配datetime-local控件）
     */
    setCurrentBeijingTimeToMinute() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0'); // 24小时制
      const minutes = String(now.getMinutes()).padStart(2, '0');
      // datetime-local 格式：YYYY-MM-DDTHH:mm
      this.receiveTime = `${year}-${month}-${day}T${hours}:${minutes}`;
    },

    /**
     * 精确获取当前北京时间（到秒，用于提交后端）
     * @returns {string} 格式化时间：YYYY-MM-DD HH:mm:ss
     */
    getCurrentExactTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0'); // 24小时制
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0'); // 真实秒数
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    /**
     * 格式化时间为24小时制（处理用户手动修改时间的情况）
     */
    formatTimeTo24h() {
      if (!this.receiveTime) return;
      const date = new Date(this.receiveTime);
      const hours = String(date.getHours()).padStart(2, '0'); // 强制24小时制
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const datePart = this.receiveTime.split('T')[0];
      this.receiveTime = `${datePart}T${hours}:${minutes}`;
    },

    /**
     * 调用后端API提交工单数据
     * @param {Object} submitData - 提交给后端的数据（炉号 + 时间）
     * @returns {Promise<Object>} 后端返回结果
     */
    async submitWorkOrderToApi(submitData) {
      try {
        // 替换为你的实际后端接口地址
        const response = await axios.post('/api/cailiao_plan_data/maopi_songyang', submitData, {
          headers: {
            'Content-Type': 'application/json',
            // 如需认证，添加Token（根据项目实际情况调整）
            // 'Authorization': `Bearer ${localStorage.getItem('userToken')}`
          }
        });
        console.log(response)
        return response.data;
      } catch (error) {
        // 错误信息提取（适配不同后端返回格式）
        if (error.response?.data?.message) {
          throw new Error(error.response.data.message);
        } else if (error.message.includes('Network Error')) {
          throw new Error('网络连接失败，请检查网络设置');
        } else if (error.message.includes('timeout')) {
          throw new Error('请求超时，请稍后重试');
        } else {
          throw new Error('提交失败，系统异常');
        }
      }
    },

    /**
     * 从后端获取最新工单列表（用于提交后刷新表格）
     */
    async fetchWorkOrders() {
      this.isTableLoading = true;
      try {
        const response = await axios.get('/api/cailiao_plan_data/maopisongyang_db', {
          // 可选：添加分页参数（根据后端需求调整）
          // params: { pageNum: 1, pageSize: 100 }
        });
        console.log(response["data"])
        // 假设后端返回格式：{ code: 200, data: [], message: '' }
        if(response["data"].length>0){
          // console.log("dayu le ma ")
          this.workOrders = response["data"]
        }else{
          alert("meiyou ")
        }
      } catch (error) {
        this.showErrorToast(error.message);
        this.workOrders = [];
      } finally {
        this.isTableLoading = false;
      }
    },

    /**
     * 显示成功提示弹窗
     * @param {string} msg - 提示信息
     */
    showSuccessToast(msg = '工单提交成功') {
      this.showSuccess = true;
      clearTimeout(this.successTimer);
      // 3秒后自动关闭
      this.successTimer = setTimeout(() => {
        this.showSuccess = false;
      }, 3000);
    },

    /**
     * 显示错误提示弹窗
     * @param {string} msg - 错误信息
     */
    showErrorToast(msg) {
      this.errorMsg = msg;
      this.showError = true;
      clearTimeout(this.errorTimer);
      // 5秒后自动关闭
      this.errorTimer = setTimeout(() => {
        this.showError = false;
        this.errorMsg = '';
      }, 5000);
    },

    /**
     * 回车事件核心处理逻辑
     * 流程：验证输入 → 获取精确时间 → 调用API → 刷新表格 → 重置状态
     */
    async handleEnter() {
      // 1. 输入验证（防止空炉号提交）
      const furnaceNum = this.furnaceNumber.trim();
      if (!furnaceNum) {
        this.showErrorToast('请输入有效的炉号');
        return;
      }

      // 2. 防止重复提交（加载中禁用再次提交）
      if (this.isLoading) return;
      this.isLoading = true;

      try {
        // 3. 获取当前精确时间（提交瞬间的时间，包含真实秒数）
        const exactTime = this.getCurrentExactTime();

        // 4. 准备提交给后端的数据（与后端接口字段保持一致）
        const submitData = {
          furnaceNumber: furnaceNum, // 炉号
          receiveTime: exactTime // 精确到秒的接收时间（24小时制）
          // 可选：添加其他后端需要的字段
          // createBy: localStorage.getItem('username'),
          // inspectionType: '材料送检'
        };

        // 5. 调用后端API提交数据
        console.log(submitData)
        const apiResult = await this.submitWorkOrderToApi(submitData);
        console.log("????",apiResult)
        // 6. API提交成功（根据后端返回状态判断）
        if (apiResult === "True") {
          this.showSuccessToast(apiResult.message || '提交成功');

          // 7. 刷新表格数据（从后端重新获取，保证数据一致性）
          await this.fetchWorkOrders();

          // 8. 重置输入状态（方便连续添加）
          this.furnaceNumber = ''; // 清空炉号输入框
          this.setCurrentBeijingTimeToMinute(); // 重置时间控件为当前时间
          document.getElementById('furnaceNumber').focus(); // 保持输入框焦点
        } else {
          // 后端返回业务错误（如炉号已存在等）
          throw new Error(apiResult.message || '提交失败');
        }
      } catch (error) {
        // 9. 错误处理（显示错误提示）
        this.showErrorToast(error.message);
      } finally {
        // 10. 无论成功失败，都关闭加载状态
        this.isLoading = false;
      }
    }
  }
};
</script>

<style scoped>
/* --- 基础与布局 --- */
.work-order-app {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  background-color: #f4f7fa;
  min-height: 100vh;
  padding: 20px;
  color: #334155;
  position: relative;
}

.app-header h1 {
  text-align: center;
  color: #1e293b;
  margin-bottom: 30px;
  font-weight: 600;
  font-size: 24px;
}

.main-content {
  max-width: 1000px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* --- 卡片组件 --- */
.card {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  position: relative;
}

.card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
}

.card-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e2e8f0;
  background-color: #f8fafc;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #0f172a;
}

.card-body {
  padding: 24px;
}

/* --- 表单组件 --- */
.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.form-group {
  margin-bottom: 16px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #475569;
  font-size: 14px;
}

.form-control {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #cbd5e1;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.2s, box-shadow 0.2s;
  box-sizing: border-box;
}

.form-control:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-control:disabled {
  background-color: #f8fafc;
  cursor: not-allowed;
  opacity: 0.7;
}

.form-hint {
  margin-top: 4px;
  font-size: 12px;
  color: #94a3b8;
}

.form-error {
  margin-top: 4px;
  font-size: 12px;
  color: #ef4444;
  margin-bottom: 0;
}

/* --- 加载状态 --- */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 100;
}

.loading-spinner {
  width: 30px;
  height: 30px;
  border: 3px solid #e2e8f0;
  border-top: 3px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

.loading-spinner.small {
  width: 20px;
  height: 20px;
  border-width: 2px;
}

.loading-text {
  color: #475569;
  font-size: 14px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* --- 搜索组件 --- */
.search-container {
  margin-bottom: 20px;
}

.search-input {
  padding-left: 40px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%2394a3b8' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='11' cy='11' r='8'%3E%3C/circle%3E%3Cline x1='21' y1='21' x2='16.65' y2='16.65'%3E%3C/line%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: 14px center;
}

/* --- 表格组件 --- */
.table-responsive {
  max-height: 500px;
  overflow-y: auto;
  border-radius: 8px;
  border: 1px solid #f1f5f9;
}

.work-order-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.work-order-table th {
  background-color: #f8fafc;
  color: #0f172a;
  font-weight: 600;
  padding: 14px 20px;
  text-align: left;
  position: sticky;
  top: 0;
  z-index: 10;
  border-bottom: 2px solid #e2e8f0;
  border-right: 1px solid #f1f5f9;
}

.work-order-table th:last-child {
  border-right: none;
}

.table-row td {
  padding: 14px 20px;
  border-bottom: 1px solid #f1f5f9;
  border-right: 1px solid #f1f5f9;
  transition: background-color 0.2s;
}

.table-row td:last-child {
  border-right: none;
}

.table-row:hover td {
  background-color: #f1f5f9;
}

.no-data {
  text-align: center;
  padding: 60px 20px;
  color: #94a3b8;
  border-right: none !important;
}

.no-data p:first-child {
  font-size: 24px;
  margin-bottom: 8px;
}

.no-data-hint {
  font-size: 14px;
}

.loading-data {
  text-align: center;
  padding: 60px 20px;
  color: #94a3b8;
  border-right: none !important;
}

/* --- 提示弹窗 --- */
.toast {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 12px 20px;
  border-radius: 8px;
  color: white;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  z-index: 1000;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  animation: slideIn 0.3s ease-out;
}

.success-toast {
  background-color: #10b981;
}

.error-toast {
  background-color: #ef4444;
}

.icon-check::before {
  content: "✓";
  font-weight: bold;
}

.icon-error::before {
  content: "!";
  font-weight: bold;
  display: inline-block;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background-color: white;
  color: #ef4444;
  text-align: center;
  line-height: 16px;
  font-size: 12px;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* --- 响应式设计 --- */
@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
  }
  .card-body {
    padding: 16px;
  }
  .work-order-table th,
  .table-row td {
    padding: 12px 16px;
  }
  .app-header h1 {
    font-size: 20px;
  }
  .toast {
    left: 20px;
    right: 20px;
    text-align: center;
  }
}
</style>